package ru.lenwp.operation.admin;

import ru.lenwp.dao.UserDao;
import ru.lenwp.util.ConsoleUtil;
import ru.lenwp.util.IOUtils;
import ru.lenwp.context.Context;
import ru.lenwp.model.Admin;
import ru.lenwp.model.OperationInfo;
import ru.lenwp.model.User;
import ru.lenwp.operation.Operation;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import static ru.lenwp.StringConstants.*;

/**
 * Created by Lenar on 04.08.2014.
 */
public class SaveUsersOperation implements Operation {

    private final Context context;

    public SaveUsersOperation(Context context) {
        this.context = context;
    }

    public void saveUserList() {
        FileWriter fwr = null;
        StringBuilder sb = new StringBuilder();
        try {
            List<User> userList = context.getUserDao().allUser();
            String fileName = ConsoleUtil.askString();
            fwr = new FileWriter(fileName);

            for (int i = 0; i < userList.size(); i++) {
                writeUserToFile(fwr, sb, userList.get(i));
            }
        } catch (Exception e) {
            System.out.println("Файл не найден");
            e.printStackTrace();
        } finally {
            IOUtils.close(fwr);
        }
    }

    private void writeUserToFile(FileWriter fwr, StringBuilder sb, User currentUser) throws IOException {
        sb.setLength(0);
        appendNameAndValue(sb, ROLE_LABEL, role(currentUser));
        appendNameAndValue(sb, NUMBER, String.valueOf(currentUser.getId()));
        appendNameAndValue(sb, LOGIN, currentUser.getLogin());
        appendNameAndValue(sb, FIRST_NAME_CAPTION, currentUser.getFirstName());
        appendNameAndValue(sb, LAST_NAME_CAPTION, currentUser.getLastName());
        appendNameAndValue(sb, SUR_NAME, currentUser.getSurName());
        appendNameAndValue(sb, BIRTH_DATE, new SimpleDateFormat().format(currentUser.getDate()));
        appendNameAndValue(sb, EMAIL_CAPTION, currentUser.getEmail());
        sb.append("\n");
        fwr.write(sb.toString());
        fwr.flush();
    }

    private void appendNameAndValue(StringBuilder sb, String name, String value) {
        sb.append(name).append(nameValueDelimiter).append(value).append(segmentDelimiter);
    }

    private String role(User user) {
        return user instanceof Admin ? ADMIN_LABEL : CLIENT_LABEL;
    }

    @Override
    public OperationInfo execute() {
        saveUserList();
        return null;
    }

    @Override
    public String getOperationName() {
        return "Сохранение пользователя";
    }
}
